package com.qiwenshare.file.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiwenshare.common.result.RestResult;
import com.qiwenshare.common.util.DateUtil;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.component.InitData;
import com.qiwenshare.file.domain.RoleMenu;
import com.qiwenshare.file.domain.SysRole;
import com.qiwenshare.file.mapper.RoleMenuMapper;
import com.qiwenshare.file.mapper.SysRoleMapper;
import com.qiwenshare.file.api.RoleService;
import com.qiwenshare.file.mapper.UserMapper;
import com.qiwenshare.file.vo.SysRoleVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Role)表服务实现类
 *
 * @author makejava
 * @since 2023-09-23 08:59:05
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public IPage<SysRoleVo> getRoleList(String roleName, Long currentPage, Long pageCount) {
        Page<SysRoleVo> page = new Page<>(currentPage, pageCount);
        IPage<SysRoleVo> rolePage = sysRoleMapper.selectPageVo(page, SysRole.builder()
                .roleName(roleName)
                .build());
        List<SysRoleVo> roleList = rolePage.getRecords().stream().peek(r-> {
            r.setCreateUser(InitData.getStaffNameByUserId(r.getCreateUserId()));
            r.setModifyUser(InitData.getStaffNameByUserId(r.getModifyUserId()));
        }).collect(Collectors.toList());
        rolePage.setRecords(roleList);
        return rolePage;
    }

    @Override
    public List<SysRole> queryAllRoleList() {
        return sysRoleMapper.selectList(new QueryWrapper<>(SysRole.builder().build()));
    }

    @Override
    public List<Long> queryListByUser(String userId) {
        return sysRoleMapper.queryListByUser(userId);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param roleId 主键
     * @return 实例对象
     */
    @Override
    public SysRole queryById(Long roleId) {
        return this.sysRoleMapper.queryById(roleId);
    }

    /**
     * 新增数据
     *
     * @param sysRole 实例对象
     * @return 实例对象
     */
    @Override
    public RestResult<String> insert(SysRole sysRole, List<String> menuIds) {
        sysRole.setCreateTime(DateUtil.getCurrentTime());
        sysRole.setCreateUserId(SessionUtil.getSession().getUserId());

        this.sysRoleMapper.insert(sysRole);

        List<RoleMenu> finalRoleMenuList = new ArrayList<>();
        menuIds.forEach(m-> {
            finalRoleMenuList.add(RoleMenu.builder()
                    .menuId(m)
                    .roleId(sysRole.getRoleId())
                    .build());
        });
        if (CollectionUtils.isNotEmpty(finalRoleMenuList)) {
            roleMenuMapper.insertBatch(finalRoleMenuList);
        }
        return RestResult.success();
    }

    /**
     * 修改数据
     *
     * @param sysRole 实例对象
     * @return 实例对象
     */
    @Override
    public RestResult<String> update(SysRole sysRole, List<String> menuIds) {
        sysRole.setModifyTime(DateUtil.getCurrentTime());
        sysRole.setModifyUserId(SessionUtil.getSession().getUserId());
        roleMenuMapper.delete(new QueryWrapper<>(RoleMenu.builder()
                .roleId(sysRole.getRoleId())
                .build()));
        List<RoleMenu> roleMenuList = new ArrayList<>();
        List<RoleMenu> finalRoleMenuList = roleMenuList;
        menuIds.forEach(m-> {
            finalRoleMenuList.add(RoleMenu.builder()
                            .menuId(m)
                            .roleId(sysRole.getRoleId())
                    .build());
        });
        roleMenuMapper.insertBatch(finalRoleMenuList);
        this.sysRoleMapper.update(sysRole);

        return RestResult.success();
    }

    /**
     * 通过主键删除数据
     *
     * @param roleId 主键
     * @return 是否成功
     */
    @Override
    public RestResult deleteById(Long roleId) {
        userMapper.deleteUserRoleByRoleId(roleId);
        roleMenuMapper.delete(new QueryWrapper<>(RoleMenu.builder()
                .roleId(roleId)
                .build()));
        RestResult result=  this.sysRoleMapper.deleteById(roleId) > 0 ? RestResult.success() : RestResult.fail();

        return result;
    }
}
